const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ExerciseSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  type: {
    type: String,
    required: true
  },
  category: {
    type: String,
    enum: ['有氧运动', '抗阻训练', '柔韧与平衡']
  },
  date: {
    type: Date,
    required: true
  },
  startTime: {
    type: String,
    required: true
  },
  duration: {
    type: Number,
    required: true,
    min: 1
  },
  intensity: {
    type: Number,
    required: true,
    min: 1,
    max: 10
  },
  caloriesBurned: {
    type: Number,
    required: true
  },
  // 血糖监测相关字段，可选
  glucoseBefore: {
    type: Number
  },
  glucoseAfter: {
    type: Number
  },
  notes: {
    type: String
  },
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

// 更新时自动更新updatedAt字段
ExerciseSchema.pre('save', function(next) {
  this.updatedAt = Date.now();
  next();
});

// 计算血糖变化
ExerciseSchema.virtual('glucoseChange').get(function() {
  if (this.glucoseBefore && this.glucoseAfter) {
    return this.glucoseAfter - this.glucoseBefore;
  }
  return 0;
});

// 计算血糖变化百分比
ExerciseSchema.virtual('glucoseChangePercent').get(function() {
  if (this.glucoseBefore && this.glucoseAfter && this.glucoseBefore > 0) {
    return ((this.glucoseAfter - this.glucoseBefore) / this.glucoseBefore) * 100;
  }
  return 0;
});

// 获取运动强度描述
ExerciseSchema.virtual('intensityText').get(function() {
  if (this.intensity <= 3) return '轻度';
  if (this.intensity <= 6) return '中等';
  return '剧烈';
});

// 确保虚拟属性在JSON中显示
ExerciseSchema.set('toJSON', { virtuals: true });
ExerciseSchema.set('toObject', { virtuals: true });

// 删除运动记录时使用remove()而不是deleteOne()
ExerciseSchema.methods.remove = async function() {
  return await this.model('Exercise').deleteOne({ _id: this._id });
};

module.exports = mongoose.model('Exercise', ExerciseSchema); 